/**
 *  Duke 创建于 2018/3/22
 * 
 *  主要用于更新用户相关信息
 */


const $ = require('../utils/utils');
const config = require('../config')


/***
 * 
 * 登录流程
 * 
 * 
 * 
 */


function checkWXSession() {
    // 默认登录状态在调用前判断
    return new Promise(function (resolve, reject) {
        isVailSession().then(data => {
            resolve(data)
        }).catch(error => {
            reject(error)
        })
    })
}

function isVailSession() {

    return new Promise(function (resolve, reject) {
        wx.checkSession({
            success: function () {
                getWXCode().then(data => {
                    resolve(data)
                }).catch(error => {
                    reject(error)
                })
                console.log('#userManager_checkWXSession()_未过期,换取用户信息');
            },
            fail: function () {
                console.log('#userManager_checkWXSession()_session过期，重新获取');
                getWXCode().then(data => {
                    resolve(data)
                }).catch(error => {
                    reject(error)
                })
            }
        })
    })

}

// 用wx.login获取的code 到 server 换取 token
function getWXCode() {
    return new Promise(function (resolve, reject) {
        console.log('#userManager.js_getWXCode');
        wx.login({
            success: function (data) {
                let url = config.getOpenid + '?code=' + data.code
                $.get(url).then(data => {
                    console.log('#userManager.js_getWXCode_data', data);
                    // token 是必须返回的
                    //  若有用户存在，则存储数据，将 isLogin 存为 true 
                    //  若不存在，先保存token， 在调用登陆接口时，将token传到后台

                    wx.setStorageSync("usertoken", data.detail.usertoken)
                    if (data.code == 0) {
                        console.log('#userManager_getWXCode()_获取wx.login-code', data);
                        wx.setStorageSync("isLogin", true)
                        saveLoginInfo(data.detail.userInfo)
                        wx.setStorageSync("userPhone", data.detail.mobile)
                    } else {
                        wx.removeStorageSync('userid')
                        console.log('#userManager_getWXCode()_未查询到绑定用户', data);
                        wx.setStorageSync("isLogin", false)
                    }
                    resolve(data)
                }).catch(error => {
                    console.log('#userManager_getWXCode()_getopenid_请求错误', error);
                    wx.setStorageSync("isLogin", false)
                    reject(error)
                })
            },
            fail: function (error) {
                console.log('#userManager_getWXCode()_未获取到wx.login信息', error);
                reject(error)
            }
        })
    })
}


function aesPhoneNumber(iv, encryptedData, path = "") {

    return new Promise(function (resolve, reject) {

        // 如果有userid 说明登录状态被顶掉，重新获取code登录
        if (wx.getStorageSync("userid")) {
            console.log("#userManager()_aesPhoneNumber() 有Userid")
            checkWXSession().then(data => {
                resolve(data)
            }).catch(error => {
                console.log("#userManager()_aesPhoneNumber()没有自动登录成功", error)
                AESLogin(iv, encryptedData, path).then(data => {
                    resolve(data)
                }).catch(error => {
                    reject(error)
                })
            })
        } else {
            console.log("#userManager()_aesPhoneNumber() 没有Userid")
            AESLogin(iv, encryptedData, path).then(data => {
                resolve(data)
            }).catch(error => {
                reject(error)
            })
        }


    })

}

function AESLogin(iv, encryptedData, path = "") {
    return new Promise(function (resolve, reject) {
        let data = {
            type: 1,
            usertoken: wx.getStorageSync("usertoken"),
            iv: iv,
            encryptedData: encryptedData
        }
        let url = config.getAESInfo
        $.post(url, data).then(data => {
            console.log('getAESInfo', data)
            if (data.code != 0) {
                console.log("#userManager()_AESLogin()没有自动登录成功", data)
                reject(data)
            } else {
                console.log("#userManager()_AESLogin()自动登录成功", data)
                saveLoginInfo(data.detail.userInfo)
                wx.setStorageSync("userPhone", data.detail.moblie)
                if (path == "scanCode") {
                    wx.setStorageSync("scanIsFromLogin", true)
                }
                wx.setStorageSync("isLogin", true)
                resolve(data)

            }

        }).catch(error => {
            reject(error)
        })
    })
}






/***
 * 
 * 信息保存
 * 
 * 
 */

// 保存登陆后返回的信息
function saveLoginInfo(data) {
    wx.setStorageSync('isLogin', true)
    wx.setStorageSync('userid', data.userid);
    wx.setStorageSync('wishCount', data.wish_list_count)
    wx.setStorageSync("borrowed_count", data.borrowed_count)
    wx.setStorageSync('user_img', data.imgurl)
    wx.setStorageSync('username', data.username)

    //是否缴纳押金
    if (data.deposit_amount == 99) {
        wx.setStorageSync('deposit_flag', 1);
    } else {
        wx.setStorageSync('deposit_flag', 0);
    }

    if (data.usertoken != null && data.usertoken.length > 1) {
        wx.setStorageSync('usertoken', data.usertoken);
    }
    console.log("#userManager.js_saveLoginInfo____success", wx.getStorageSync('userPhone'), wx.getStorageSync("userid"))
}

// 将微信用户信息和userid 绑定
function bindWXUserToUser(success) {
    console.log("#userManager.js_bindOpenidToUserId()", wx.getStorageSync('userid'), wx.getStorageSync('unionid'))
    let postUrl = config.saveWxUserInfo
    let postData = {
        userid: wx.getStorageSync('userid'),
        usertoken: wx.getStorageSync('usertoken'),
        nickName: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').nickName : '',
        avatarUrl: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').avatarUrl : '',
        gender: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').gender : '',
        province: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').province : '',
        city: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').city : '',
        country: wx.getStorageSync('userinfo') ? wx.getStorageSync('userinfo').country : ''
    }
    $.post(postUrl, postData).then(data => {
        console.log("#userManager.js_WXUserInfoToUser()____success", data)
        if (success) {
            success()
        }
    })

}


// 保存 FormId
function saveMsgFormId(formId) {

    if (!wx.getStorageSync("isLogin")) {
        return
    }
    $.uploadFormid(config.hostUrl, config.appId, formId)
    console.log("#userManager.js_uploadFormid")
}


// 查询用户是否处于开柜流程中
function remindLockStatus() {

    return new Promise(function (resolve, reject) {
        if (wx.getStorageSync('userid') && wx.getStorageSync('usertoken')) {

            let params = {
                userid: wx.getStorageSync('userid'),
                usertoken: wx.getStorageSync('usertoken')
            }

            let url = $.getUrl(config.getUserInfo, params)

            wx.request({
                url: url,
                method: 'GET',
                success: res => {
                    let data = res.data
                    console.log('remind_time', data)
                    if (!res.data.detail) {
                        return
                    }

                    if (data.code == 0 && data.detail.grid_status == 1) {
                        //判断是否有柜门开着
                        wx.setStorageSync('grid_code', data.detail.grid_code);
                        console.info('柜门开着，剩余时间' + data.detail.remainseconds);
                        if (wx.getStorageSync("isBorrowing_Repair")) {
                            return
                        }
                        if (data.detail.remainseconds != 0) {
                            console.log('当前用户有开柜剩余时间在执行！');
                            var timeStart = parseInt(data.detail.remainseconds); // 秒 ;
                            //转换成 分钟:秒
                            var theTime1 = parseInt(timeStart / 60); // 分
                            if (theTime1 < 10) theTime1 = '0' + theTime1;

                            var theTime2 = parseInt(timeStart % 60); //秒
                            if (theTime2 < 10) theTime2 = '0' + theTime2;

                            wx.setStorageSync('timeStart', theTime1 + ":" + theTime2);
                            $.goto((opendoorPage), true)
                        } else {
                            $.goto((opendoorPage + '?overTimeFlag=1'), true)
                        }
                    } else {
                        if (data.code == 0 && data.detail.deposit_amount == 99) {
                            wx.setStorageSync('deposit_flag', 1);
                        } else {
                            wx.setStorageSync('deposit_flag', 0);
                        }
                        wx.setStorageSync("cash_amount", data.detail.cash_amount)
                        wx.removeStorageSync('timeStart');
                        resolve(data)
                    }
                },
                fail: error => {
                    reject(error)
                }
            })


            // $.get(url).then(data => {
            //     console.log('请求服务器获取用户开柜剩余时间信息:',data);

            //     if (data.code == 0 && data.detail.grid_status == 1) {
            //         //判断是否有柜门开着
            //         wx.setStorageSync('grid_code', data.detail.grid_code);
            //         console.info('柜门开着，剩余时间' + data.detail.remainseconds);
            //         if (wx.getStorageSync("isBorrowing_Repair")) {
            //             return
            //         }
            //         if (data.detail.remainseconds != 0) {
            //             console.log('当前用户有开柜剩余时间在执行！');
            //             var timeStart = parseInt(data.detail.remainseconds); // 秒 ;
            //             //转换成 分钟:秒
            //             var theTime1 = parseInt(timeStart / 60); // 分
            //             if (theTime1 < 10) theTime1 = '0' + theTime1;

            //             var theTime2 = parseInt(timeStart % 60); //秒
            //             if (theTime2 < 10) theTime2 = '0' + theTime2;

            //             wx.setStorageSync('timeStart', theTime1 + ":" + theTime2);
            //             $.goto((opendoorPage), true)
            //         } else {
            //             $.goto((opendoorPage + '?overTimeFlag=1'), true)
            //         }
            //     } else {
            //         if (data.code == 0 && data.detail.deposit_amount == 99) {
            //             wx.setStorageSync('deposit_flag', 1);
            //         } else {
            //             wx.setStorageSync('deposit_flag', 0);
            //         }
            //         wx.setStorageSync("cash_amount", data.detail.cash_amount)
            //         wx.removeStorageSync('timeStart');
            //         resolve(data)
            //     }
            // }).catch(error => {
            //     reject(error)
            // })

        }

        reject('NOT LOGIN')
        console.log("#userManager.js_remindLockStatus()")
    })

}




function getCurrentUserInfo() {
    return new Promise((resolve, reject) => {
        let data = {
            userid: wx.getStorageSync('userid'),
            usertoken: wx.getStorageSync('usertoken')
        }
        let url = $.getUrl(config.getUserInfo, data)
        $.get(url).then(data => {
            wx.hideLoading();

            console.log(data);
            if (data.result == 1) {
                saveLoginInfo(data.detail)
                resolve(data)
            } else {
                $.showToast(data.message)
                reject(data)
            }
        }).catch(error => {
            reject(error)
            console.log("#usermanager_getCurrentInfo_()", error)
        })
    })
}








function getUserInfo() {
    //调用登录接口
    wx.getUserInfo({
        withCredentials: true,
        success: function (res) {
            console.log('#usermanage_userinfo()____success', res);

            // TODO 需要将获取到的encryptedData 和 iv 传递给后台
        },
        fail: function (res) {
            wx.getSetting({
                success: (res) => {
                    console.log('getSetting', res);
                    if (res.authSetting['scope.userInfo'] == false || res.authSetting['scope.userLocation'] == false) {
                        wx.showModal({
                            title: '提示',
                            content: '需要您设置用户授权才能体验哦~',
                            showCancel: false,
                            confirmText: '去设置',
                            success: function (opt) {
                                wx.openSetting({
                                    success: (res) => {
                                        console.log('#usermanage_openSetting()____success', res);
                                    }
                                });
                            }
                        });
                    }
                },
            });
        }
    })
}


function checkSession() {
    return new Promise(function (resolve, reject) {
        wx.checkSession({
            success: function () {
                resolve()
            },
            fail: function () {
                wx.login({
                    success: function (data) {
                        let url = config.getOpenid + '?code=' + data.code
                        $.get(url).then(data => {
                            console.log('拉取openid成功', data);
                            if (data.code === 0) {
                                resolve()
                            }
                        }).catch(error => {
                            reject()
                        })
                    }
                })
            }
        })
    })
}








module.exports = {
    saveLoginInfo: saveLoginInfo,
    bindWXUserToUser: bindWXUserToUser,
    saveMsgFormId: saveMsgFormId,
    remindLockStatus: remindLockStatus,
    getUserInfo: getUserInfo,
    getCurrentUserInfo: getCurrentUserInfo,


    checkWXSession: checkWXSession,
    aesPhoneNumber: aesPhoneNumber,
}